package com.dao.impl;

import com.dao.IFlightDao;
import com.model.FlightModel;
import com.utils.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class FlightDaoImpl implements IFlightDao {
    private JdbcTemplate jt = new JdbcTemplate(JdbcUtils.getDs());

    @Override
    public List<FlightModel> queryAllFlights() throws Exception {
        String sql = "SELECT * FROM flights";
        return jt.query(sql, new BeanPropertyRowMapper<>(FlightModel.class));
    }

    @Override
    public List<FlightModel> searchFlights(String departureCity, String arrivalCity, String departureDate) throws Exception {
        StringBuilder sql = new StringBuilder("SELECT * FROM flights WHERE 1=1");
        List<Object> params = new ArrayList<>();

        if (departureCity != null && !departureCity.isEmpty()) {
            sql.append(" AND departure_city = ?");
            params.add(departureCity);
        }

        if (arrivalCity != null && !arrivalCity.isEmpty()) {
            sql.append(" AND arrival_city = ?");
            params.add(arrivalCity);
        }

        if (departureDate != null && !departureDate.isEmpty()) {
            sql.append(" AND DATE(departure_time) = ?");
            params.add(departureDate);
        }

        sql.append(" ORDER BY departure_time ASC");

        return jt.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(FlightModel.class));
    }
} 